<?php
namespace Home\Controller;
use Home\Model\ActivityOrderModel;
use Home\Model\ActivityModel;

//微信支付类
class WxpayController extends BaseController {
    
    public function _initialize(){
        parent::_initialize();
        $this->_order = new ActivityOrderModel();
    }
    /**
     * 提交活动订单
     */
    public function addOrder(){
        $data = I('post.');
        $activity_model = new ActivityModel();
        $activity_data = $activity_model->getActivityDetail($data['activity_id']);
        $data['user_id'] = $this->user_id;
        $data['sponsor_user_id'] = $activity_data['user_id'];//主办方id
        $data['activity_name'] = $activity_data['activity_name'];
        //区别收费和免费
        $activity_data['price'] > 1 ? $data['order_status'] = 1 : $data['order_status'] = 2;
        $activity_data['price'] > 1 ? $data['payment_status'] = 1 : $data['payment_status'] = 2;
        $data['number'] = 1;
        $data['amount'] = $activity_data['price'] * 1;
        $data['order_sn'] = self::createOrder_sn();
        $data['add_time'] = time();
        $row = $this->_order->addOrder($data);
        if($row){
            /*  $content = "恭喜您刚刚报名参加了[ {$activity_data['activity_name']} ] 的活动!";
             $jsApi = new \JsApi_pub();
             $jsApi->push_msg($this->openid, $content); */
            //echo 'ok';

            //已报名人+1
            $resutl = $activity_model->setSignupNumber($data['activity_id']);
            if($resutl){
                if($activity_data['price'] < 1){
                    $this->assign('title', '提示');
                    $this->assign('message', '恭喜你，报名成功！');
                    $this->assign('jump_url', U("Users/index"));
                    $this->assign('text', '用户中心');
                    $this->display('Public/publish_tishi');
                }else{
                    //self::js_api_call($data['order_sn']);    
                    //$this->redirect('js_api_call', array('order_sn' => $data['order_sn']));
                    header('location:'.'http://'.$_SERVER['SERVER_NAME'].'/Wxpay/js_api_call?order_sn='.$data['order_sn']);
                }
            }
            exit;
        }else{
            header('location:'.__ROOT__.'/');
        }
    }
    
    /**
     * 创建订单编号
     */
    private function createOrder_sn(){
        //订购日期
        $order_date = date('Y-m-d');
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_id;
    }
    
    
    //获取access_token过程中的跳转uri，通过跳转将code传入jsapi支付页面
    public function js_api_call($order_sn) {
        $order_sn = I('order_sn');
        if (empty($order_sn)) {
            header('location:'.__ROOT__.'/');
        }
        vendor('Weixinpay.WxPayPubHelper');
        //使用jsapi接口
        $jsApi = new \JsApi_pub();
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
       if(!$_SESSION['openid']) {    
            if (!isset($_GET['code'])){
                //触发微信返回code码
                $url = $jsApi->createOauthUrlForCode('http://activity.gdweihu.com/Wxpay/js_api_call?order_sn='.$order_sn);
                //$url = $jsApi->createOauthUrlForCode(\WxPayConf_pub::JS_API_CALL_URL);
                Header("Location: $url"); 
            }else{
                //获取code码，以获取openid
                $code = $_GET['code'];
                $jsApi->setCode($code);
                $openid = $jsApi->getOpenId();
                //var_dump($openid);
            }
        }else{
            $openid=$_SESSION['openid'];
        }
        
        $order_data = M('activity_order')->field('amount, activity_name')->where("order_sn = '$order_sn'")->find();
        
        $res = array(
            'order_sn' => $order_sn,
            'order_amount' => 0.01,//$order_data['amount']
            'activity_name' => $order_data['activity_name']
        );
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $total_fee = $res['order_amount']*100;

        //$total_fee = 1;
        $body = "订单支付{$res['order_sn']}";
        $unifiedOrder->setParameter("openid", "$openid");//用户标识
        $unifiedOrder->setParameter("body", $body);//商品描述
        //自定义订单号，此处仅作举例
        $out_trade_no = $res['order_sn'];
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no);//商户订单号 

        $unifiedOrder->setParameter("total_fee", $total_fee);//总金额
        //$unifiedOrder->setParameter("attach", "order_sn={$res['order_sn']}");//附加数据 
        $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL);//通知地址 
        $unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号 
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据 
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();
        //echo json_encode($jsApiParameters);
        $wxconf = json_decode($jsApiParameters, true);
        if ($wxconf['package'] == 'prepay_id') {
            $this->error('当前订单存在异常，不能使用支付');
        }
        $this->assign('res', $res);
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->display('jsapi');
    }
    //异步通知url，商户根据实际开发过程设定
    public function notify_url() {
        vendor('Weixinpay.WxPayPubHelper');
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];  
        /* $xml = "<xml><appid><![CDATA[wx2c7b4284e08afd13]]></appid>
         <attach><![CDATA[685-5-6]]></attach>
         <bank_type><![CDATA[CFT]]></bank_type>
         <cash_fee><![CDATA[50000]]></cash_fee>
         <fee_type><![CDATA[CNY]]></fee_type>
         <is_subscribe><![CDATA[Y]]></is_subscribe>
         <mch_id><![CDATA[1260840801]]></mch_id>
         <nonce_str><![CDATA[abcdefghijklmnopqrstuvwxyz0123456789]]></nonce_str>
         <openid><![CDATA[olPu5uK3wylKJ7tPEarETNj479gE]]></openid>
         <out_trade_no><![CDATA[201708031551113794097917]]></out_trade_no>
         <result_code><![CDATA[SUCCESS]]></result_code>
         <return_code><![CDATA[SUCCESS]]></return_code>
         <sign><![CDATA[2EB473F64187CA62E6C6768F9B166924]]></sign>
         <time_end><![CDATA[20170313175919]]></time_end>
         <total_fee>50000</total_fee>
         <trade_type><![CDATA[JSAPI]]></trade_type>
         <transaction_id><![CDATA[5007492001201703133251852188]]></transaction_id>
         </xml>"; */
        file_put_contents('xml.txt', $xml);
        
        $notify->saveData($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code", "FAIL");//返回状态码
            $notify->setReturnParameter("return_msg", "签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code", "SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        file_put_contents('returnXml.txt', $returnXml);
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
        //$log_name = "notify_url.log";//log文件路径
        //$this->log_result($log_name, "【接收到的notify通知】:\n".$xml."\n");
        $parameter = $notify->xmlToArray($xml);
        file_put_contents('parameter.txt', $parameter);
        //$this->log_result($log_name, "【接收到的notify通知】:\n".$parameter."\n");
        if($notify->checkSign() == TRUE){
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                //$this->log_result($log_name, "【通信出错】:\n".$xml."\n");
                //更新订单数据【通信出错】设为无效订单
                echo 'error';
            }
            else if($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                //$this->log_result($log_name, "【业务出错】:\n".$xml."\n");
                //更新订单数据【通信出错】设为无效订单
                echo 'error';
            }
            else{
                file_put_contents('wxpay_log.txt', "【支付成功】:\n".$xml."\n",FILE_APPEND);
                //$this->log_result($log_name, "【支付成功】:\n".$xml."\n");
                //我这里用到一个process方法，成功返回数据后处理，返回地数据具体可以参考微信的文档
                if ($this->process($parameter)) {
                    //处理成功后输出success，微信就不会再下发请求了
                    echo 'success';
                }else {
                    //没有处理成功，微信会间隔的发送请求
                    echo 'error';
                }
            }
        }
    }
    //订单处理
    private function process($parameter) {
        $order_model = M('activity_order');
        $data = array(
            'payment_status' => 2,
            'order_status' => 2,
            'pay_time' => time()
        );
        $order_model->where("order_sn = '{$parameter['out_trade_no']}'")->save($data);
        //此处应该更新一下订单状态，商户自行增删操作
        /*
        * 返回的数据最少有以下几个
        * $parameter = array(
            'out_trade_no' => xxx,//商户订单号
            'total_fee' => XXXX,//支付金额
            'openid' => XXxxx,//付款的用户ID
        );
        */
        return true;
    }
}
?>